package com.clkj.zhonghui.pojo.common;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

public class OSSUtil {

    /**
     * 阿里OSS上传工具类
     * @param file 文件
     * @param path 存储文件夹路径
     * @return
     */
    public static String uploadingImg(MultipartFile file,String path){
        try {
            String fileName = "";
            String endpoint = ImgApi.endpoint;
            String accessKeyId = ImgApi.accessKeyId;
            String accessKeySecret = ImgApi.accessKeySecret;
            String bucketName = ImgApi.bucketName;

            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            // 获取文件名称
            fileName = file.getOriginalFilename();

            // 以下操作主要是把上传的文件分类放到oss存储，这样防止上传相同的文件名，会把前一个文件覆盖掉。 start
            // 在文件名称里面添加随机唯一的值
//                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//                // yuy76t5rew01.jpg
//                fileName = uuid + fileName;
//                // 2 把文件按照日期进行分类
//                // 获取当前日期,格式化
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
//                String datePath = sdf.format(new Date());
            // 拼接
            String randomStringByLength = Util.getRandomIntegerByLength(3);
            String picName = System.currentTimeMillis()+randomStringByLength+fileName.substring(fileName.lastIndexOf("."));
            fileName = path + "/" + picName;

            // end
            // 调用oss方法实现上传
            // 第一个参数 Bucket名称
            // 第二个参数 上传到oss文件路径和文件名称
            // 第三个参数 上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();

            // 把上传之后文件路径返回，需要把上传到阿里云oss路径手动拼接出来
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            System.out.println(url);
            return picName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//    /**
//     * 下载文件
//     * @param yuan
//     * @param muDi
//     */
    public void downLoadFileAvatar(String yuan, File muDi) {
        //获取oss上传配置文件中的参数

        String endpoint = ImgApi.endpoint;
        String accessKeyId = ImgApi.accessKeyId;
        String accessKeySecret = ImgApi.accessKeySecret;
        String bucketName = ImgApi.bucketName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
        // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
        File muDiFile=new File(muDi,System.currentTimeMillis()+(yuan.substring(yuan.indexOf("."))));
        ossClient.getObject(new GetObjectRequest(bucketName, yuan),muDiFile);
        // 关闭OSSClient。
        ossClient.shutdown();
    }
//
//    /**
//     * 批量下载文件,此处主要是给Controller层提供一个OSS的Object类
//     * objectName示例：download/file.xsl,()这里是oss文件列表中 文件路径和文件名
//     */
    public static OSSObject downloadOssFile(String objectName) {

        try {
            String endpoint = ImgApi.endpoint;
            String accessKeyId = ImgApi.accessKeyId;
            String accessKeySecret = ImgApi.accessKeySecret;
            String bucketName = ImgApi.bucketName;

//            String tmp  = "https://" + bucketName + "." + endpoint + "/" + objectName;
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            return ossObject;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除多个文件
     */
    public static boolean deleteListFile(List<String> fileNames) {

        String endpoint = ImgApi.endpoint;
        String accessKeyId = ImgApi.accessKeyId;
        String accessKeySecret = ImgApi.accessKeySecret;
        String bucketName = ImgApi.bucketName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件。
            // 填写需要删除的多个文件完整路径。文件完整路径中不能包含Bucket名称。
//            例如
//            List<String> fileNames = new ArrayList<String>();
//            fileNames.add("exampleobjecta.txt");
//            fileNames.add("testfolder/sampleobject.txt");
//            fileNames.add("exampleobjectb.txt");

//            //处理多余路径
//            List<String> pics = new ArrayList<>();
//            for (String fileName : fileNames) {
//                String objectName = fileName.substring(45);
//                pics.add(objectName);
//            }

            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(fileNames).withEncodingType("url"));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            try {
                for (String obj : deletedObjects) {
                    String deleteObj = URLDecoder.decode(obj, "UTF-8");
                    System.out.println(deleteObj);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return true;
    }




}
